package convertfiles.controller;

import java.io.IOException;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.conversion.Asset;
import com.google.appengine.api.conversion.Conversion;
import com.google.appengine.api.conversion.ConversionResult;
import com.google.appengine.api.conversion.ConversionService;
import com.google.appengine.api.conversion.ConversionServiceFactory;
import com.google.appengine.api.conversion.Document;
import com.google.appengine.api.urlfetch.FetchOptions;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

public class Home extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws IOException {
		convertHtml2Pdf(resp);
	}

	public static void convertHtml2PNG(HttpServletResponse resp) {
		try {
			Asset asset = new Asset("text/html", "<b>Hello the world</b>".getBytes(), "test.html");
			Document document = new Document(asset);
			Conversion conversion = new Conversion(document, "image/png");
			
			ConversionService service = ConversionServiceFactory.getConversionService();
			ConversionResult result = service.convert(conversion);
			if (result.success()) {
				for (Asset assetR: result.getOutputDoc().getAssets()) {
					resp.setContentType("image/png");
					resp.getOutputStream().write(assetR.getData());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public static void convertHtml2Text(HttpServletResponse resp) {
		try {
			Asset asset = new Asset("text/html", "<b>Hello the world</b>".getBytes(), "convertfiles.html");
			Document document = new Document(asset);
			Conversion conversion = new Conversion(document, "text/plain");
			
			ConversionService service = ConversionServiceFactory.getConversionService();
			ConversionResult result = service.convert(conversion);
			if (result.success()) {
				for (Asset assetR: result.getOutputDoc().getAssets()) {
					resp.setContentType("text/plain");
					resp.getOutputStream().write(assetR.getData());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void convertHtml2Pdf(HttpServletResponse resp) {
		try {
			Asset asset = new Asset("text/html", "<b>Hello the world</b>".getBytes(), "convertfiles.html");
			Document document = new Document(asset);
			Conversion conversion = new Conversion(document, "application/pdf");
			
			ConversionService service = ConversionServiceFactory.getConversionService();
			ConversionResult result = service.convert(conversion);
			if (result.success()) {
				for (Asset assetR: result.getOutputDoc().getAssets()) {
					resp.setContentType("application/pdf");
					resp.getOutputStream().write(assetR.getData());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void convertImage2Html(HttpServletResponse resp) {
		try {
			byte[] img = null;
			
			URLFetchService fetchService =
	            URLFetchServiceFactory.getURLFetchService();
			// Fetch the image at the location given by the url query string parameter
			String urlString = "https://www.google.com.vn/logos/2012/yoshizawa12-hp.jpg";
			URL url = new URL(urlString);
			// Fetch the image at the location given by the url query string parameter
			FetchOptions fetchOptions =FetchOptions.Builder.withDefaults();
			fetchOptions.setDeadline((double)30*60);
			HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, fetchOptions);
	        HTTPResponse fetchResponse = fetchService.fetch(request);
	        
	        String fetchResponseContentType = null;
	        for (HTTPHeader header : fetchResponse.getHeaders()) {
	            // For each request header, check whether the name equals
	            // "Content-Type"; if so, store the value of this header
	            // in a member variable
	            if (header.getName().equalsIgnoreCase("content-type")) {
	                fetchResponseContentType = header.getValue();
	                break;
	            }
	        }
	        
	        if (fetchResponseContentType != null) {
	        	//check extension
	        	String extension = "png";
	        	
				if (fetchResponseContentType.equalsIgnoreCase("image/bmp")) {
					extension = "bmp";
				}
				if (fetchResponseContentType.equalsIgnoreCase("image/gif")) {
					extension = "gif";
				}
				if (fetchResponseContentType.equalsIgnoreCase("image/jpeg")) {
					extension = "jpeg";
				}
				if (fetchResponseContentType.equalsIgnoreCase("image/png")) {
					extension = "png";
				}
	        	
	        	//Convert
	        	img = (byte[]) fetchResponse.getContent();
				Asset asset = new Asset(fetchResponseContentType, img, "convertfiles." + extension);
				Document document = new Document(asset);
				Conversion conversion = new Conversion(document, "text/html");
				
				ConversionService service = ConversionServiceFactory.getConversionService();
				ConversionResult result = service.convert(conversion);
				if (result.success()) {
					for (Asset assetR: result.getOutputDoc().getAssets()) {
						resp.setContentType("text/html");
						resp.getOutputStream().write(assetR.getData());
					}
				}
	        }
	        
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void convertImage2Text(HttpServletResponse resp) {
		try {
			byte[] img = null;
			URLFetchService fetchService =
	            URLFetchServiceFactory.getURLFetchService();
			// Fetch the image at the location given by the url query string parameter
			String urlString = "https://www.google.com.vn/logos/2012/yoshizawa12-hp.jpg";
			URL url = new URL(urlString);
			// Fetch the image at the location given by the url query string parameter
			FetchOptions fetchOptions =FetchOptions.Builder.withDefaults();
			fetchOptions.setDeadline((double)30*60);
			HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, fetchOptions);
	        HTTPResponse fetchResponse = fetchService.fetch(request);
	        
	        String fetchResponseContentType = null;
	        for (HTTPHeader header : fetchResponse.getHeaders()) {
	            // For each request header, check whether the name equals
	            // "Content-Type"; if so, store the value of this header
	            // in a member variable
	            if (header.getName().equalsIgnoreCase("content-type")) {
	                fetchResponseContentType = header.getValue();
	                break;
	            }
	        }
	        
	        if (fetchResponseContentType != null) {
	        	//check extension
	        	String extension = "png";
	        	
				if (fetchResponseContentType.equalsIgnoreCase("image/bmp")) {
					extension = "bmp";
				}
				if (fetchResponseContentType.equalsIgnoreCase("image/gif")) {
					extension = "gif";
				}
				if (fetchResponseContentType.equalsIgnoreCase("image/jpeg")) {
					extension = "jpeg";
				}
				if (fetchResponseContentType.equalsIgnoreCase("image/png")) {
					extension = "png";
				}
	        	
	        	//Convert
	        	img = (byte[]) fetchResponse.getContent();
				Asset asset = new Asset(fetchResponseContentType, img, "convertfiles." + extension);
				Document document = new Document(asset);
				Conversion conversion = new Conversion(document, "text/plain");
				
				ConversionService service = ConversionServiceFactory.getConversionService();
				ConversionResult result = service.convert(conversion);
				if (result.success()) {
					for (Asset assetR: result.getOutputDoc().getAssets()) {
						resp.setContentType("text/plain");
						resp.getOutputStream().write(assetR.getData());
					}
				}
	        }
	        
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void convertImage2Pdf(HttpServletResponse resp) {
		try {
			byte[] img = null;
			URLFetchService fetchService =
	            URLFetchServiceFactory.getURLFetchService();
			// Fetch the image at the location given by the url query string parameter
			String urlString = "https://www.google.com.vn/logos/2012/yoshizawa12-hp.jpg";
			URL url = new URL(urlString);
			// Fetch the image at the location given by the url query string parameter
			FetchOptions fetchOptions =FetchOptions.Builder.withDefaults();
			fetchOptions.setDeadline((double)30*60);
			HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, fetchOptions);
	        HTTPResponse fetchResponse = fetchService.fetch(request);
	        
	        String fetchResponseContentType = null;
	        for (HTTPHeader header : fetchResponse.getHeaders()) {
	            // For each request header, check whether the name equals
	            // "Content-Type"; if so, store the value of this header
	            // in a member variable
	            if (header.getName().equalsIgnoreCase("content-type")) {
	                fetchResponseContentType = header.getValue();
	                break;
	            }
	        }
	        
	        if (fetchResponseContentType != null) {
	        	//Convert
	        	img = (byte[]) fetchResponse.getContent();
	        	resp.setContentType("image/jpeg");
				resp.getOutputStream().write(img);
				/*Asset asset = new Asset(fetchResponseContentType, img, "convertfiles.jpg");
				Document document = new Document(asset);
				Conversion conversion = new Conversion(document, "application/pdf");
				
				ConversionService service = ConversionServiceFactory.getConversionService();
				ConversionResult result = service.convert(conversion);
				if (result.success()) {
					for (Asset assetR: result.getOutputDoc().getAssets()) {
						resp.setContentType("application/pdf");
						resp.getOutputStream().write(assetR.getData());
					}
				}*/
	        }
	        
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
